//
//  NetworkTools.swift
//  云Sir的微博
//
//  Created by 赵云 on 15/10/10.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit
import AFNetworking

/// 错误的类别标记
private let ZYErrorDomainName = "com.itheima.error.network"
//
private enum ZYNetworkError: Int {
    case emptyDataError = -1
    case emptyTokenError = -2
    
    /// 错误描述
    private var errorDescrption: String {
        switch self {
        case .emptyDataError: return "空数据"
        case .emptyTokenError: return "Token 为空"
        }
    }
    
    /// 根据枚举类型，返回对应的错误
    private func error() -> NSError {
        return NSError(domain: ZYErrorDomainName, code: rawValue, userInfo: [ZYErrorDomainName: errorDescrption])
    }
}

/// 网络访问方法
private enum ZYNetworkMethod: String {
    case GET = "GET"
    case POST = "POST"
}


class NetworkTools: AFHTTPSessionManager {
    
    //应用程序信息
    let clientId = "955495214"
    let appSecret = "c60c024fccc93920a62ff314c42528c8"
    let redirectUri = "http://www.baidu.com"
    
    // MARK: - 类型定义
    /// 网络回调类型别名
    typealias ZYNetFinished = (result: [String: AnyObject]?, error: NSError?)->()
    
    /// 单例
    static let sharedTools: NetworkTools = {
        
        //http要注意s
        let baseUrl = NSURL(string: "https://api.weibo.com/")!
        
        let tools = NetworkTools(baseURL: baseUrl)
        
        //设置数据的解析类型
        tools.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as Set<NSObject>
        
        return tools
        
    }()
    
    /// 检查并生成token字典
    private func tokenDict(finished: ZYNetFinished) -> [String: AnyObject]? {
        //判断token是否存在
        if UserAccount.sharedAccount?.access_token == nil {
            
            let error = ZYNetworkError.emptyTokenError.error()
            print(error)
            //TODO:
            finished(result: nil, error: error)
            
            return nil
        }
        
        //生成字典并返回
        return ["access_token": UserAccount.sharedAccount!.access_token!]
        
    }
    
    //MARK : - 加载微博数据
    func loadStatus(finished: ZYNetFinished){
        //判断token是否存在
        guard let params = tokenDict(finished) else{
            return
        }
        
        //代码运行至此,params一定会有值
        let urlString = "2/statuses/home_timeline.json"
        
        request(ZYNetworkMethod.GET, urlString: urlString, params: params, finished: finished)
        
    }
    
    
    //MARK: - 加载用户数据 --- 做网络访问  获取字典
    func loadUserInfo(uid: String, finished: ZYNetFinished){
        
        //判断token是否存在
        guard var params = tokenDict(finished) else{
            return
        }
        
        let urlString = "2/users/show.json"
        
        params["uid"] = uid
        
        //发送网络请求

        // 发送网络请求
        // 提示：如果参数不正确，首先用 option + click 确认参数类型
        request(ZYNetworkMethod.GET, urlString: urlString, params: params, finished: finished)
    }
    
    //MARK: - OAuth授权
    //返回oauth授权地址
    func oauthUrl() -> NSURL {
    
    let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)"
    
    return NSURL(string: urlString)!
    }
    
    //加载TOKEN  闭包回调
    func loadAccessToken(code: String, finished: ZYNetFinished){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        /**
        client_id   (申请应用时分配的AppKey。) 
        client_secret  (申请应用时分配的AppSecret)
        grant_type (请求的类型，填写authorization_code)
        code (调用authorize获得的code值)
        redirect_uri (回调地址，需需与注册应用里的回调地址一致)
            */
        //强烈强调:键值不能打空格
        let params = ["client_id":clientId,
            "client_secret":appSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":redirectUri]
        
      request(ZYNetworkMethod.POST, urlString: urlString, params: params, finished: finished)

    }
    
    
    // MARK: - 封装 AFN 网络方法，便于替换网络访问方法，第三方框架的网络代码全部集中在此
    /// AFN 网络请求 GET / POST
    ///
    /// :param: method    HTTP 方法 GET / POST
    /// :param: urlString URL 字符串
    /// :param: params    字典参数
    /// :param: finished  完成回调
    private func request(method: ZYNetworkMethod, urlString: String, params: [String: AnyObject], finished: ZYNetFinished) {
        
        // 1. 定义成功的闭包
        let successCallBack: (NSURLSessionDataTask!, AnyObject!) -> Void = { (_, JSON) -> Void in
            
            if let result = JSON as? [String: AnyObject] {
                // 有结果的回调
                finished(result: result, error: nil)
            } else {
                // 没有错误，同时没有结果
                print("没有数据 \(method) Request \(urlString)")
                
                finished(result: nil, error: ZYNetworkError.emptyDataError.error())
            }
        }
        
        // 2. 定义失败的闭包
        let failedCallBack: (NSURLSessionDataTask!, NSError!) -> Void = { (_, error) -> Void in
            print(error)
            
            finished(result: nil, error: error)
        }
        
        // 3. 根据 method 来选择执行的方法
        switch method {
        case .GET:
            GET(urlString, parameters: params, success: successCallBack, failure: failedCallBack)
        case .POST:
            POST(urlString, parameters: params, success: successCallBack, failure: failedCallBack)
        }
    }

    
    }
